package com.lh.ssm.web;

import com.lh.ssm.domain.Cart;
import com.lh.ssm.domain.User;
import com.lh.ssm.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;
    @GetMapping("/cartCreate")
    public String create(int pid,HttpSession session,HttpServletRequest request) {

        User user = (User) session.getAttribute("loginUser");
        int uid = user.getId();
        System.out.println(pid);

        int result = cartService.createCart(pid,uid);
        System.out.println(result);
        if(result > 0){
            return "cartSuccess";
        }
        request.setAttribute("msg","添加失败！");
        return "message";
    }

    @GetMapping("/cartShow")
    public String show(int uid,HttpServletRequest request){

        List<Cart> list = cartService.findAllByUid(uid);
        request.setAttribute("list",list);
        return "cart";
    }

    @GetMapping("/cartUpdate")
    public String update(HttpSession session,int cid, int cnum, BigDecimal price) {
        User user = (User) session.getAttribute("loginUser");
        int uid = user.getId();
        int result = cartService.updateCartById(cid,cnum,price);
        return "forward:/cartShow?uid="+uid;

    }

    @GetMapping("/cartDelete")
    public String delete(int cid,HttpSession session){
        User user = (User) session.getAttribute("loginUser");
        int uid = user.getId();
        //根据id,删除对应的购物车记录
        int result = cartService.deleteCartById(cid);

        //重新展示购物车列表页面
        return "forward:/cartShow?uid="+uid;
    }

    @GetMapping("/cartClear")
    public String clear(int uid){

        int result = cartService.clearCart(uid);
        return "forward:/cartShow?uid="+uid;
    }

}
